package org.juiceshop.gm;

import groovy.lang.Closure;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.sound.midi.Sequence;

import org.juiceshop.gm.midi.MidiSequence;
import org.juiceshop.gm.midi.SequenceDumper;
import org.juiceshop.gm.midi.SimplePlayer;

public class Music extends NoteFactory {

	private SimplePlayer _midiPlayer = new SimplePlayer();

		
	public ScoreX score (Closure scriptClosure) {
		return ScoreX.create(scriptClosure);
	}
	
	public ScoreX score (MusicObject obj) {
		return ScoreX.create(obj);
	}
	
	
	public ScoreX score() {
		return new ScoreX();
	}
	
	public void play (Score score) {
		play (score.getSequence());
	}

	public void play (ScoreX score) {
		play (score.getSequence());
	}

	public void play (Closure closure) {
		play(score(closure));
	}
	
	public void play (MusicObject obj) {
		play(score(obj));
	}
	
	public void play (Sequence sequence) {
		System.out.print("Playing...");
        _midiPlayer.play(sequence);
        System.out.println("finished");
	}
	
	public void play (MidiSequence sequence) {
		System.out.print("Playing...");
//        _midiPlayer.play(sequence);
		byte[] bytes = sequence.toByteArray();
		_midiPlayer.play(bytes);
        System.out.println("finished");
	}

	public void dump (Sequence sequence) {
		new SequenceDumper().dump(sequence);
	}
	
	public void dump (MidiSequence sequence) {
		sequence.print();
	}
	
	public void save (MidiSequence sequence) {
		byte[] bytes = sequence.toByteArray();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("music.mid");
			fos.write(bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos!=null) {
				try {
					fos.close();
				} catch (IOException e) {
					throw new Error(e);
				}
			}
		}
	}

}
